import { useRef, useState, useEffect } from 'react';
import { View, Text, Modal, Pressable, ScrollView, Image, Alert, ActivityIndicator, FlatList } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import * as DocumentPicker from 'expo-document-picker';
import * as FileSystem from 'expo-file-system';
import { getToken } from '../utils/auth/tokenStorage';
import { API_BASE_URL, STORAGE_TYPE } from '../constants/api';
import { FileSystemAcceptedUploadHttpMethod } from 'expo-file-system';

interface FileUploadItem {
  file: {
    uri: string;
    name: string;
    type?: string;
  };
  id: string;
  progress: number;
  size?: number;
  fileId?: string;
  status: 'pending' | 'uploading' | 'success' | 'error';
  url?: string;
  error?: string;
}

interface BatchReceiptUploaderProps {
  visible: boolean;
  onClose: () => void;
  onBatchUploadComplete: (fileUrls: {fileName: string, url: string, fileId: string, size: number}[]) => void;
  themeSerialNo: string;
}

export default function BatchReceiptUploader({ visible, onClose, onBatchUploadComplete, themeSerialNo }: BatchReceiptUploaderProps) {
  const [files, setFiles] = useState<FileUploadItem[]>([]);
  const [isUploading, setIsUploading] = useState(false);

  // 监听visible属性变化，当模态框关闭时清空文件列表
  useEffect(() => {
    if (!visible) {
      setFiles([]);
    }
  }, [visible]);

  // 封装关闭函数，确保关闭时清空列表
  const handleClose = () => {
    setFiles([]);
    onClose();
  };

  // 从相册选择图片
  const pickImage = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        allowsMultipleSelection: true, // 启用多选
        quality: 0.8,
      });

      if (!result.canceled && result.assets.length > 0) {
        // 处理多张图片
        const newFiles: FileUploadItem[] = result.assets.map(asset => ({
          file: {
            uri: asset.uri,
            name: asset.fileName || `image_${new Date().getTime()}.jpg`,
            type: 'image/jpeg',
          },
          size: asset.fileSize,
          id: `${asset.uri}_${Date.now()}`,
          progress: 0,
          status: 'pending',
        }));

        setFiles(prev => [...prev, ...newFiles]);
      }
    } catch (error) {
      Alert.alert('错误', '选择图片失败');
      console.error(error);
    }
  };

  // 拍照
  const takePhoto = async () => {
    try {
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      
      if (status !== 'granted') {
        Alert.alert('权限错误', '需要相机权限才能拍照');
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        quality: 0.8,
      });

      if (!result.canceled && result.assets.length > 0) {
        const asset = result.assets[0];
        const newFile: FileUploadItem = {
          file: {
            uri: asset.uri,
            name: `camera_${new Date().getTime()}.jpg`,
            type: 'image/jpeg',
          },
          size: asset.fileSize,
          id: `${asset.uri}_${Date.now()}`,
          progress: 0,
          status: 'pending',
        };

        setFiles(prev => [...prev, newFile]);
      }
    } catch (error) {
      Alert.alert('错误', '拍照失败');
      console.error(error);
    }
  };

  // 选择文档
  const pickDocument = async () => {

    console.log("选中了文件");
    try {
      const result = await DocumentPicker.getDocumentAsync({
        type: ['image/*', 'application/pdf'],
        multiple: true,
      });

      if (result.canceled === false && result.assets.length > 0) {
        const newFiles: FileUploadItem[] = result.assets.map(asset => {
          // 确定文件类型
          let fileType = 'image/jpeg';
          if (asset.mimeType) {
            fileType = asset.mimeType;
          } else if (asset.name.endsWith('.pdf')) {
            fileType = 'application/pdf';
          } else if (asset.name.endsWith('.png')) {
            fileType = 'image/png';
          }

          return {
            file: {
              uri: asset.uri,
              name: asset.name,
              type: fileType,
            },
            id: `${asset.uri}_${Date.now()}`,
            size: asset.size,
            progress: 0,
            status: 'pending',
          };
        });

        setFiles(prev => [...prev, ...newFiles]);
      }
    } catch (error) {
      Alert.alert('错误', '选择文档失败');
      console.error(error);
    }
  };

  // 移除文件
  const removeFile = (id: string) => {
    setFiles(prev => prev.filter(file => file.id !== id));
  };

  // 上传单个文件到OSS
  const uploadFileToOSS = async (fileItem: FileUploadItem): Promise<{success: boolean, url?: string, error?: string, fileId: string, size: number}> => {
    try {
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }

      // 获取OSS上传签名
      const signatureUrl = `${API_BASE_URL}/api/oss/get-signature?fileName=${encodeURIComponent(fileItem.file.name)}&themeSerialNo=${themeSerialNo}&token=${encodeURIComponent(token)}`;
      
      // 使用fetch获取签名
      const signatureResponse = await fetch(signatureUrl, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      });
      
      const signData = await signatureResponse.json();
      
      if (!signData.success) {
        throw new Error(signData.message || '获取上传签名失败');
      }
      console.log("获取上传签名成功:",signData) 

      const { url, formData, fileId } = signData.data;
      


      // 创建表单数据
      const apiUrl = url;
      const uploadParams: Record<string, string> = {};
      
      // 添加OSS所需的参数
      Object.entries(formData).forEach(([key, value]) => {
        if (typeof value === 'string') {
          uploadParams[key] = value;
        }
      });
      let storageType = STORAGE_TYPE;
      let method:FileSystemAcceptedUploadHttpMethod = 'PUT';
      if(storageType === 's3'){
        method = `PUT`;
      }else if(storageType === 'oss'){
        method = `POST`;
      }
      

      // 使用FileSystem.uploadAsync上传文件
      const uploadResult = await FileSystem.uploadAsync(
        apiUrl,
        fileItem.file.uri,
        {
          httpMethod: method,
          uploadType: FileSystem.FileSystemUploadType.MULTIPART,
          fieldName: 'file',
          mimeType: fileItem.file.type,
          parameters: uploadParams,
          headers: {
            'Accept': 'application/json'
          }
        }
      );

      // 创建进度更新的模拟 (由于expo-file-system不支持进度回调，我们模拟它)
      let progress = 0;
      const updateProgress = () => {
        if (progress < 100) {
          progress += 10;
          setFiles(prev => prev.map(f => 
            f.id === fileItem.id ? { ...f, progress, status: 'uploading', fileId:formData.key } : f
          ));
          
          if (progress < 100) {
            setTimeout(updateProgress, 200);
          }
        }
      };
      
      // 开始模拟进度更新
      updateProgress();

      // 处理上传结果
      if (uploadResult.status >= 200 && uploadResult.status < 300) {
        // 设置为100%完成
        setFiles(prev => prev.map(f => 
          f.id === fileItem.id ? { ...f, progress: 100, status: 'success', fileId:formData.key } : f
        ));
        
        // 成功返回
        return { 
          success: true, 
          url: `${url}/${formData.key}`,
          fileId:formData.key,
          size: fileItem.size!,
        };
      } else {
        // 上传失败
        setFiles(prev => prev.map(f => 
          f.id === fileItem.id ? { ...f, status: 'error', error: '上传失败' } : f
        ));
        
        throw new Error(`上传失败: ${uploadResult.status}`);
      }
    } catch (error) {
      console.error('上传文件错误:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '上传失败',
        fileId: '',
        size: 0
      };
    }
  };

  // 批量上传全部文件
  const uploadAllFiles = async () => {

    if (files.length === 0) {
      Alert.alert('提示', '请先选择要上传的文件');
      return;
    }

    if (isUploading) {
      Alert.alert('提示', '正在上传中，请稍候');
      return;
    }

    setIsUploading(true);
    Alert.alert('上传中', `正在上传 ${files.length} 个文件...`);

    try {
      // 并行上传所有文件
      const uploadPromises = files.map(async (fileItem) => {
        // 跳过已上传成功的
        if (fileItem.status === 'success') return fileItem;
        
        // 将状态设置为上传中
        setFiles(prev => prev.map(f => 
          f.id === fileItem.id ? { ...f, status: 'uploading', progress: 0, fileId: '' } : f
        ));
        
        const result = await uploadFileToOSS(fileItem);
        console.log("上传结果:",result) 
        // 更新文件状态
        setFiles(prev => prev.map(f => 
          f.id === fileItem.id ? { 
            ...f, 
            status: result.success ? 'success' : 'error',
            progress: result.success ? 100 : f.progress,
            url: result.url,
            fileId: result.fileId,
            error: result.error
          } : f
        ));
        fileItem.status = result.success ? 'success' : 'error';
        fileItem.progress = result.success ? 100 : fileItem.progress;
        fileItem.url = result.url;
        fileItem.fileId = result.fileId;
        fileItem.size = fileItem.size;
        return { ...fileItem, ...result };
      });

      const results = await Promise.all(uploadPromises);
      const successFiles = results.filter(f => f.status === 'success' && f.url);
      
      if (successFiles.length > 0) {
        // 格式化成功的文件URL列表
        const fileUrls = successFiles.map(f => ({
          fileName: f.file.name,
          size: f.size || 0,
          fileId: f.fileId || '',
          url: f.url || ''
        }));
        
        // 触发完成回调
        onBatchUploadComplete(fileUrls);
        
        Alert.alert('上传完成', `成功上传 ${successFiles.length} 个文件`);
        // 清空文件列表
        setFiles([]);
        handleClose();
      } else {
        Alert.alert('上传失败', '没有文件上传成功');
      }
    } catch (error) {
      console.error('批量上传错误:', error);
      Alert.alert('上传错误', '批量上传发生错误');
    } finally {
      setIsUploading(false);
    }
  };

  // 取消上传
  const handleCancel = () => {
    if (isUploading) {
      Alert.alert(
        '确认取消',
        '正在上传文件，确定要取消吗？',
        [
          { text: '继续上传', style: 'cancel' },
          { 
            text: '确认取消', 
            style: 'destructive',
            onPress: () => {
              setIsUploading(false);
              handleClose();
            }
          }
        ]
      );
    } else {
      handleClose();
    }
  };

  // 清空文件列表
  const clearFiles = () => {
    if (isUploading) {
      Alert.alert('提示', '正在上传中，无法清空');
      return;
    }
    setFiles([]);
  };

  // 渲染进度条
  const renderProgressBar = (progress: number) => (
    <View className="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
      <View 
        className="h-full bg-blue-500" 
        style={{ width: `${progress}%` }} 
      />
    </View>
  );

  // 渲染文件图标
  const renderFileIcon = (fileName: string) => {
    if (fileName.toLowerCase().endsWith('.pdf')) {
      return <Ionicons name="document-text" size={24} color="#f87171" />;
    } else {
      return <Ionicons name="image" size={24} color="#60a5fa" />;
    }
  };

  // 渲染文件状态图标
  const renderStatusIcon = (status: string, error?: string) => {
    switch (status) {
      case 'success':
        return <Ionicons name="checkmark-circle" size={20} color="#10b981" />;
      case 'error':
        return <Ionicons name="alert-circle" size={20} color="#ef4444" title={error} />;
      case 'uploading':
        return <ActivityIndicator size="small" color="#3b82f6" />;
      default:
        return null;
    }
  };

  return (
    <Modal
      visible={visible}
      transparent
      animationType="slide"
      onRequestClose={handleCancel}
    >
      <View className="flex-1 justify-end bg-black/50">
        <View className="bg-white rounded-t-3xl p-6 h-3/4">
          <View className="items-center mb-4">
            <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
            <Text className="text-xl font-bold">批量上传发票</Text>
          </View>

          {/* 文件列表 */}
          <View className="flex-1">
            {files.length === 0 ? (
              <View className="flex-1 items-center justify-center">
                <Ionicons name="cloud-upload-outline" size={48} color="#d1d5db" />
                <Text className="mt-4 text-gray-400">点击下方按钮选择文件上传</Text>
                <Text className="text-gray-400 text-sm">支持图片和PDF文件</Text>
              </View>
            ) : (
              <FlatList
                data={files}
                keyExtractor={(item) => item.id}
                renderItem={({ item }) => (
                  <View className="border border-gray-200 rounded-lg p-3 mb-2">
                    <View className="flex-row justify-between items-center mb-2">
                      <View className="flex-row items-center flex-1">
                        {renderFileIcon(item.file.name)}
                        <View className="ml-2 flex-1">
                          <Text className="font-medium" numberOfLines={1}>{item.file.name}</Text>
                          <Text className="text-xs text-gray-500">
                            {item.size ? `${(item.size / 1024).toFixed(1)} KB` : ''}
                          </Text>
                        </View>
                      </View>
                      <View className="flex-row items-center">
                        {renderStatusIcon(item.status, item.error)}
                        <Pressable
                          className="ml-2 p-1"
                          onPress={() => removeFile(item.id)}
                          disabled={isUploading}
                        >
                          <Ionicons name="close-circle" size={20} color="#6b7280" />
                        </Pressable>
                      </View>
                    </View>
                    {renderProgressBar(item.progress)}
                  </View>
                )}
              />
            )}
          </View>

          {/* 功能按钮 */}
          <View className="pt-4">
            {files.length === 0 ? (
              <View className="flex-row gap-3">
                <Pressable 
                  className="flex-1 flex-row items-center justify-center p-3 bg-blue-50 rounded-xl"
                  onPress={pickDocument}
                  disabled={isUploading}
                >
                  <Ionicons name="document-outline" size={20} color="#3b82f6" />
                  <Text className="ml-2 text-blue-600 font-medium">选择文件</Text>
                </Pressable>
                
                <Pressable 
                  className="flex-1 flex-row items-center justify-center p-3 bg-green-50 rounded-xl"
                  onPress={pickImage}
                  disabled={isUploading}
                >
                  <Ionicons name="images-outline" size={20} color="#10b981" />
                  <Text className="ml-2 text-green-600 font-medium">选择图片</Text>
                </Pressable>
                
                <Pressable 
                  className="flex-1 flex-row items-center justify-center p-3 bg-purple-50 rounded-xl"
                  onPress={takePhoto}
                  disabled={isUploading}
                >
                  <Ionicons name="camera-outline" size={20} color="#8b5cf6" />
                  <Text className="ml-2 text-purple-600 font-medium">拍照</Text>
                </Pressable>
              </View>
            ) : (
              <View className="flex-row gap-3">
                <Pressable 
                  className="flex-1 flex-row items-center justify-center p-3 bg-gray-50 rounded-xl"
                  onPress={clearFiles}
                  disabled={isUploading}
                >
                  <Text className="text-gray-700 font-medium">清空</Text>
                </Pressable>
                
                <Pressable 
                  className="flex-1 flex-row items-center justify-center p-3 bg-blue-500 rounded-xl"
                  onPress={uploadAllFiles}
                  disabled={isUploading || files.length === 0}
                >
                  <Text className="text-white font-medium">
                    {isUploading ? '上传中...' : '开始上传'}
                  </Text>
                </Pressable>
              </View>
            )}
            
            <Pressable 
              className="mt-3 p-3 items-center justify-center"
              onPress={handleCancel}
            >
              <Text className="text-gray-500">取消</Text>
            </Pressable>
          </View>
        </View>
      </View>
    </Modal>
  );
} 